<script setup>
	import {reactive, ref} from "vue";
	import productApi from "@/api/product/product.js";
	import {ElMessage, ElMessageBox} from "element-plus";
	import {Delete, Plus, Download, Upload, Message, Edit, Search} from "@element-plus/icons-vue";
	
	const list = ref([])
	const total = ref(0)
	
	//分页信息和搜索条件
	const productQuery = reactive({
		name: '',
		category1Id: '',
		category2Id: '',
		category3Id: '',
		page: 1,
		limit: 10
	})
	//分类搜索
	const searchCategoryIdList = ref([])
	
	const categoryProps = ref({
		value: 'id',
		label: 'name',
		lazy: true,
		checkStrictly: true,
		lazyLoad(node, resolve) {
			//刚开始点击级联框,node.value=='undefined'
			//所有一级分类的父分类是0：node.value=0
			if (typeof node.value == 'undefined') {
				node.value = 0
			}
			categoryApi.selectByParentId(node.value).then(result => {
				if (result.code === 0) {
					const {data} = result
					data.forEach(categoryVO => {
						categoryVO.leaf = !categoryVO.hasChildren
					})
					
					//返回数据
					resolve(result.data)
				}
			})
		}
	})
	
	//表格数据
	const loadData = () => {
		productApi.list(productQuery).then(result => {
			list.value = result.data.records
			list.value.forEach(item => {
				if (item.carouselImage != null) {
					item.carouselImage = item.carouselImage.split(',')
				}
			})
			total.value = result.data.total
		})
	}
	
	loadData()
	
	//搜索
	const onSearch = () => {
		productQuery.category1Id = ''
		productQuery.category2Id = ''
		productQuery.category3Id = ''
		if (searchCategoryIdList.value != undefined) {
			if (searchCategoryIdList.value.length == 1) {
				productQuery.category1Id = searchCategoryIdList.value[0]
				
			} else if (searchCategoryIdList.value.length == 2) {
				productQuery.category1Id = searchCategoryIdList.value[0]
				productQuery.category2Id = searchCategoryIdList.value[1]
				
			} else if (searchCategoryIdList.value.length == 3) {
				productQuery.category1Id = searchCategoryIdList.value[0]
				productQuery.category2Id = searchCategoryIdList.value[1]
				productQuery.category3Id = searchCategoryIdList.value[2]
			}
		}
		productQuery.page = 1
		loadData()
	}
	
	//单个删除
	const deleteById = (id) => {
		ElMessageBox.confirm(
			'确认删除吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			.then(() => {
				productApi.deleteById(id).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success',})
					} else {
						ElMessage.error(result.msg)
					}
					//刷新表格
					loadData()
				})
			})
	}
	
	//批量删除
	const ids = ref([])
	const handleSelectionChange = (rows) => {
		ids.value = rows.map(row => row.id)
		console.log(ids.value);
	}
	const deleteAll = () => {
		ElMessageBox.confirm(
			'确认删除吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			//点击确认删除
			.then(() => {
				ids.value = ids.value.join(',')
				productApi.deleteAll(ids.value).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success',})
					} else {
						ElMessage.error(result.msg)
					}
					//刷新表格
					loadData()
				})
			})
	}
	
	//添加、编辑
	const dialogFormVisible = ref(false)
	const product = ref({})
	const title = ref()
	const categoryIdList = ref([])
	const categoryProps2 = ref({
		value: 'id',
		label: 'name',
		lazy: true,
		lazyLoad(node, resolve) {
			//刚开始点击级联框,node.value=='undefined'
			//所有一级分类的父分类是0：node.value=0
			if (typeof node.value == 'undefined') {
				node.value = 0
			}
			categoryApi.selectByParentId(node.value).then(result => {
				if (result.code === 0) {
					const {data} = result
					data.forEach(categoryVO => {
						categoryVO.leaf = !categoryVO.hasChildren
					})
					
					//返回数据
					resolve(result.data)
				}
			})
		}
	})
	const carouselImageList = ref([])   //轮播图列表
	const carouseList = ref([])   //轮播图列表
	//上传轮播图  方法1
	/*const handleCarouselRemove = (uploadFile, uploadFiles) => {
		carouselImageList.value.splice(carouselImageList.value.indexOf(uploadFile.url), 1)
	}
	const handleCarouselSuccess = (result, uploadFile) => {
		if(result.code==0){
			carouselImageList.value.push(result.data)
		}
	}*/
	//级联框选择
	const categoryChange = () => {
		product.value.category1Id = categoryIdList.value[0]
		product.value.category2Id = categoryIdList.value[1]
		product.value.category3Id = categoryIdList.value[2]
	}
	//点击"添加"
	const showAddDialog = () => {
		dialogFormVisible.value = true
		title.value = '添加'
		product.value = {}
		categoryIdList.value = []
		carouseList.value = []
	}
	//点击"编辑"
	const showUpdateDialog = (id) => {
		dialogFormVisible.value = true
		title.value = '编辑'
		product.value = {}
		productApi.selectById(id).then(result => {
			product.value = result.data
			categoryIdList.value = [product.value.category1Id, product.value.category2Id, product.value.category3Id]
			carouseList.value = []
			if(product.value.carouselImage!=null){
				carouselImageList.value = product.value.carouselImage.split(',')
				carouselImageList.value.forEach(item => {
					carouseList.value.push({url: item})
				})
			}
			carouselImageList.value=[]
		})
	}
	//确认按钮
	const addOrUpdate = () => {
		//用“,”拼接轮播图字符串
		const carouseImage=ref([])
		carouseList.value.forEach(item=>{
			if(item.response){
				carouseImage.value.push(item.response.data)
			}else {
				carouseImage.value.push(item.url)
			}
		})
		product.value.carouselImage = carouseImage.value.join(',')
		if (product.value.id) {  //有值，编辑
			productApi.update(product.value).then(result => {
				if (result.code === 0) {
					ElMessage({message: result.msg, type: 'success',})
					dialogFormVisible.value = false
				} else {
					ElMessage.error(result.msg)
				}
				//刷新表格
				loadData()
			})
		} else {   //无值，添加
			// product.value.carouselImage = carouselImageList.value.join(',')
			productApi.add(product.value).then(result => {
				console.log(product.value.carouselImage)
				if (result.code === 0) {
					ElMessage({message: result.msg, type: 'success',})
					dialogFormVisible.value = false
				} else {
					ElMessage.error(result.msg)
				}
				//刷新表格
				loadData()
			})
		}
	}
	
	//更改状态
	const handleSwitchChange = (row) => {
		productApi.updateStatus(row.id, row.status).then(result => {
			if (result.code === 0) {
				ElMessage.success(result.msg)
			} else {
				ElMessage.error(result.msg)
			}
		})
	}
	
	//导出Excel
	const exportExcel = () => {
		productApi.exportExcel().then(result => {
			let blob = new Blob([result], {type: "application/xlsx"});
			let url = window.URL.createObjectURL(blob);
			const link = document.createElement("a"); // 创建a标签
			link.href = url;
			link.download = "博客列表.xlsx"; // 重命名文件
			link.click();
			URL.revokeObjectURL(url);
		})
	}
	
	const success = () => {
		ElMessage({message: '导入成功！', type: 'success',})
	}
	
	//富文本编辑器
	const onEditorChange = (content) => {
		product.value.content = content
	}
	import {useTokenStore} from '@/store/token.js'
	import WangEditor from "@/components/WangEditor.vue";
	import categoryApi from "@/api/product/category.js";
	
	const tokenStore = useTokenStore();
	const headers = ref({
		//携带token传递到后端
		Authorization: tokenStore.token
	});
	
	//上传单个图片成功后
	const handleAvatarSuccess = (result) => {
		product.value.image = result.data
	}
	
	//重置按钮
	const originData = () => ({
		name: "",
		category1Id: '',
		category2Id: '',
		category3Id: '',
		beginUpdateTime: null,
		endUpdateTime: null
	});
	const resetForm = () => {
		Object.assign(productQuery, originData());
		searchCategoryIdList.value = ''
		loadData();
	};
</script>

<template>
	<el-card class="">
		<template #header>
			<div class="header">
				<el-button type="success" :icon="Plus" @click="showAddDialog">添加</el-button>
				<el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
				<el-button type="primary" :icon="Download" @click="exportExcel">导出Excel</el-button>
				<el-upload
					class="upload-demo"
					multiple=""
					method="post"
					action="/api/blog/importExcel"
					name="file"
					style="margin-left: 10px"
					accept=".xlsx,.xls"
					:show-file-list="false"
					:on-success="success"
					:headers="headers">
					<el-button type="primary" :icon="Upload">导入Excel</el-button>
				</el-upload>
			</div>
		</template>
		<el-form :inline="true">
			<el-form-item label="名字">
				<el-input v-model="productQuery.name" placeholder="请输入名字" clearable/>
			</el-form-item>
			<el-form-item label="分类">
				<el-cascader
					:props="categoryProps"
					style="width: 100%"
					v-model="searchCategoryIdList"
					clearable
				/>
			</el-form-item>
			<el-form-item label="更新时间">
				<el-date-picker
					v-model="productQuery.beginUpdateTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="开始时间"
				/>
				-
				<el-date-picker
					v-model="productQuery.endUpdateTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="结束时间"
				/>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
				<el-button @click="resetForm" round>重置</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="list" style="width: 100%" stripe border ref="multipleTableRef"
				  @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center"/>
			<el-table-column fixed="left" sortable prop="id" label="ID" align="center"/>
			<el-table-column prop="name" label="名字" width="160" align="center"/>
			<el-table-column prop="category1Name" label="一级分类" min-width="110" align="center"/>
			<el-table-column prop="category2Name" label="二级分类" min-width="110" align="center"/>
			<el-table-column prop="category3Name" label="三级分类" min-width="110" align="center"/>
			<el-table-column prop="image" label="主图" align="center">
				<template #default="scope">
					<img :src="scope.row.image" style="max-height: 40px; max-width: 120px;"/>
				</template>
			</el-table-column>
			<el-table-column
				prop="carouselImage"
				label="轮播图"
				#default="scope"
				width="200" align="center">
				<div style="height: 50px;float: left;">
					<img
						v-for="(item, index) in scope.row.carouselImage"
						:key="index"
						:src="item"
						width="50"
					/>
				</div>
			</el-table-column>
			<el-table-column prop="status" label="商品状态" align="center" width="130">
				<template #default="scope">
					<el-switch
						v-model="scope.row.status"
						class="ml-2"
						inline-prompt
						size="large"
						active-text="上架"
						:active-value="1"
						inactive-text="下架"
						:inactive-value="0"
						@change="handleSwitchChange(scope.row)"
					/>
				</template>
			</el-table-column>
			<el-table-column prop="updateTime" label="更新时间" align="center" width="200"/>
			<el-table-column fixed="right" label="操作" min-width="200" align="center">
				<template #default="{row}">
					<!--					<el-button type="info" :icon="Message" circle @click="handleClick(row.id)"/>-->
					<el-button type="warning" :icon="Edit" round @click="showUpdateDialog(row.id)">编辑</el-button>
					<el-button type="danger" :icon="Delete" round @click="deleteById(row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			v-model:current-page="productQuery.page"
			v-model:page-size="productQuery.limit"
			:page-sizes="[5, 10, 15, 20]"
			:size="size"
			:disabled="disabled"
			:background="background"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
			@change="loadData"
			style="margin-top: 20px; justify-content: flex-end"
		/>
	</el-card>
	
	<!--添加、编辑弹出框-->
	<el-dialog v-model="dialogFormVisible" :title="title" width="70%" :lock-scroll="false">
		<el-form :model="product">
			<el-form-item label="名字" :label-width="100">
				<el-input v-model="product.name" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="分类" :label-width="100">
				<el-cascader
					style="width: 100%;"
					:props="categoryProps2"
					v-model="categoryIdList"
					@change="categoryChange"
				/>
			</el-form-item>
			<el-form-item label="产品标题" :label-width="100">
				<el-input v-model="product.title" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="产品描述" :label-width="100">
				<el-input
					v-model="product.intro"
					style="width: 240px"
					:autosize="{ minRows: 2, maxRows: 4 }"
					type="textarea"
					placeholder="请输入产品描述"
				/>
			</el-form-item>
			<el-form-item label="产品售价" :label-width="100">
				<el-input v-model="product.price" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="产品价格" :label-width="100">
				<el-input v-model="product.productPrice" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="产品库存" :label-width="100">
				<el-input v-model="product.stock" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="主图" :label-width="100">
				<el-upload
					class="avatar-uploader"
					action="/api/product/upload"
					:show-file-list="false"
					:on-success="handleAvatarSuccess"
					:headers="headers"
				>
					<img v-if="product.image" :src="product.image" class="avatar"/>
					<el-icon v-else class="avatar-uploader-icon">
						<Plus/>
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="轮播图" :label-width="100">
				<el-upload
					v-model:file-list="carouseList"
					action="/api/product/upload"
					list-type="picture-card"
					multiple
					:headers="headers">
<!--	方法1				:on-success="handleCarouselSuccess"
					:on-remove="handleCarouselRemove"
					-->
					<el-icon>
						<Plus/>
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="商品详情" :label-width="100">
				<WangEditor :initValue="product.content" @getEditorContent="onEditorChange"
							v-if="dialogFormVisible" @close="dialogFormVisible = false">
				</WangEditor>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取消</el-button>
				<el-button type="primary" @click="addOrUpdate">
					确认
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
	
	.upload-demo {
		display: inline;
		vertical-align: top;
	}
</style>
<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}
	
	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}
	
	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

</style>